package com.journey.org.ui.home

import android.annotation.SuppressLint
import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableArrayList
import com.journey.org.BR
import com.journey.org.R
import com.journey.org.app.HttpManager
import com.journey.org.app.requestBase
import com.journey.org.app.requestHttpManager
import com.journey.org.app.requestPlayAndroid
import com.journey.org.entity.ArticleEntity
import com.journey.org.entity.PlayAndroidBannerEntity
import com.journey.org.ui.search.SearchActivity
import com.journey.org.ui.web.WebActivity
import com.mvvmhabit.org.base.BaseViewModel
import com.mvvmhabit.org.base.MultiItemViewModel
import com.mvvmhabit.org.binding.command.BindingAction
import com.mvvmhabit.org.binding.command.BindingCommand
import com.mvvmhabit.org.binding.command.BindingConsumer
import com.mvvmhabit.org.bus.event.SingleLiveEvent
import me.tatarka.bindingcollectionadapter2.ItemBinding
import me.tatarka.bindingcollectionadapter2.OnItemBind

/**
 * @Date: 2020/11/17 14:15
 * @Author:小妖
 * @Description:首页
 */
class HomeViewModel(application: Application) : BaseViewModel(application) {

    // 进入搜索界面
    val onEnterSearchCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            startActivity(SearchActivity::class.java, null)
        }
    })

    // 下拉刷新
    val onClickRefreshCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            items.clear()
            loadBannerData()
        }
    })

    // 下拉刷新
    val onClickAgainLoadCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            items.clear()
            loadBannerData()
        }
    })

    // 上拉加载更多
    val onClickLoadMoreCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            // loadWeekHottestList("GanHuo", false)
        }
    })

    /**************************************** 新的banner ***********************************/

    val onClickBannerItemCommand =
        BindingCommand(object : BindingConsumer<PlayAndroidBannerEntity> {
            override fun call(t: PlayAndroidBannerEntity) {
                val bundle = Bundle()
                bundle.putString("loadUrl", t.url)
                bundle.putString("title", t.title)
                startActivity(WebActivity::class.java, bundle)
            }
        })

    val bannerData = ObservableArrayList<PlayAndroidBannerEntity>()

    val onPagerLengthEvent = SingleLiveEvent<Int>()

    @SuppressLint("CheckResult")
    fun loadBannerData() {
        loadHeaderContent()
        loadWeekHottestList("Article", true)
//        loadWeekHottestList("GanHuo", true)
        requestPlayAndroid<List<PlayAndroidBannerEntity>> {
            onStart {
                showLoadDialog()
            }
            onLoader {
                HttpManager.getInstance().loadPlayAndroidBannerList()!!
            }
            onSuccess {
                if (it.isNotEmpty()) {
                    it.forEach { item ->
                        println("banner的size:${item.url}")
                        item.pictureAddr = item.imagePath
                        bannerData.add(item)
                    }
                }
            }
            onComplete {
                dismissLoadDialog()
            }
        }
    }

    /**************************************** RecycleView ***********************************/

    val itemBinding = ItemBinding.of(OnItemBind<MultiItemViewModel<HomeViewModel>>
    { itemBinding, _, item ->
        when (item?.getItemType().toString()) {
            "header" -> {
                itemBinding.set(BR.viewModel, R.layout.home_header_item)
            }
            "body" -> {
                itemBinding.set(BR.viewModel, R.layout.home_body_item)
            }
            "title" -> {
                itemBinding.set(BR.viewModel, R.layout.home_title_item)
            }
            "one_pic_body" -> { // 一张图片
                itemBinding.set(BR.viewModel, R.layout.home_body_one_pic_item)
            }
            "two_pic_body" -> { // 两张图片
                itemBinding.set(BR.viewModel, R.layout.home_body_tow_pic_item)
            }
            "three_pic_body" -> { // 三张图片
                itemBinding.set(BR.viewModel, R.layout.home_body_three_pic_item)
            }
        }
    })
    val items = ObservableArrayList<MultiItemViewModel<HomeViewModel>>()

    private fun loadHeaderContent() {
        val headerViewModel = HomeHeaderItemViewModel(this)
        headerViewModel.multiItemType("header")
        items.add(headerViewModel)
    }

    private fun loadWeekHottestList(category: String, isFirst: Boolean) {
        if (category == "Article" && isFirst) {
            val articleTitle =
                HomeTitleItemViewModel(this@HomeViewModel, "本周最\uD83D\uDD25文章")
            articleTitle.multiItemType("title")
            items.add(articleTitle)
            loadArticleList()
        } else if (category == "GanHuo" && isFirst) {
            val ganHuoTitle =
                HomeTitleItemViewModel(this@HomeViewModel, "本周最\uD83D\uDD25干货")
            ganHuoTitle.multiItemType("title")
            items.add(ganHuoTitle)
        }
    }

    /**
     * 获取文章列表
     */
    private fun loadArticleList() {
        val params = HashMap<String, Any>()
        params["limit"] = 10
//        params["name"] = ""
        params["page"] = 1
        params["queryMode"] = "page"
        requestBase<List<ArticleEntity>> {
            requestHttpManager {
                onLoader {
                    loadArticleList(params)!!
                }
                onSuccess {
                    if (it.isNotEmpty()) {
                        it.forEach { item ->
                            if (item.fileUrls == null) {
                                val itemViewModel = HomeItemViewModel(this@HomeViewModel, item)
                                itemViewModel.multiItemType("body")
                                items.add(itemViewModel)
                            } else {
                                item.urls = item.fileUrls.split(",")
                                val itemViewModel = HomeItemViewModel(this@HomeViewModel, item)
                                when {
                                    item.urls.isEmpty() -> {
                                        itemViewModel.multiItemType("body")
                                    }
                                    item.urls.size == 1 -> {
                                        itemViewModel.multiItemType("one_pic_body")
                                    }
                                    item.urls.size == 2 -> {
                                        itemViewModel.multiItemType("one_pic_body")
                                    }
                                    else -> {
                                        itemViewModel.multiItemType("three_pic_body")
                                    }
                                }
                                items.add(itemViewModel)
                            }
                        }
                    }
                }
            }
        }
    }

}